package com.ldaptest;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.ldap.InitialLdapContext;

public class LdapQuery {
    public static final String CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    public static final String DOMAIN = "@fhtesc.fiberhome.com.cn";// fhtesc
    public static final String URL = "ldap://10.78.13.128:389";

    public static void main(String[] args) {
        LdapQuery lp = new LdapQuery();

        try {

            // String dn =
            // "CN=test_add_1,OU=SDMP,OU=AllUsers,DC=fhtesc,DC=fiberhome,DC=com,DC=cn";
            String dn = "test_3" + DOMAIN;// “Distinguished Name”

            lp.init(dn, "1qaz2wsx");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public DirContext init(String dn, String password) throws Exception {
        try {
            Hashtable<String, String> enviroment = new Hashtable<String, String>();

            enviroment.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
            enviroment.put(Context.PROVIDER_URL, URL);
            enviroment.put(Context.SECURITY_AUTHENTICATION, "simple");

            enviroment.put(Context.SECURITY_PRINCIPAL, dn);
            enviroment.put(Context.SECURITY_CREDENTIALS, password);

            DirContext dirContext = new InitialLdapContext(enviroment, null);

            if (dirContext != null) {
                System.out.println("success");
            }

            return dirContext;

        } catch (Exception e) {
            System.out.println("failed");

            throw e;
        }
    }
}
